package com.zzq.interceptor;

import com.alibaba.fastjson.JSON;
import com.zzq.utils.IResult;
import com.zzq.utils.JWTUtil;
import com.zzq.utils.Log;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HeaderTokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        //解决中文乱码问题
        request.setCharacterEncoding("utf-8");

        response.setCharacterEncoding("utf-8");
        //解决response中writer乱码方案
        response.setHeader("Content-Type", "text/html;charset=UTF-8");


        IResult iResult = null;
        // 获取请求头中的token验证字符串
        String headerToken = request.getHeader("token");
        // 检测当前页面，设置当前页不是登录页面时就对其进行拦截
        // 具体方法就是检测URL中有没有login字符串
        if (headerToken == null) {
            // 如果没有token，返回错误信息
            iResult = new IResult();
            iResult.setMsg("请先登录！");
        }
        try {
            // 对token更新与验证
            headerToken = JWTUtil.updateToken(headerToken);
//                Log.LogWarn("token验证通过，并且续期了");
        } catch (Exception e) {
            iResult = new IResult();
            iResult.setMsg("token验证出现异常！");
        }
        // 如果有错误信息
        if (iResult != null) {
            response.getWriter().write(JSON.toJSONString(iResult));
            return false;
        } else {
            // 将token加入返回的header中
            response.setHeader("token", headerToken);
            return true;
        }
    }
}